package com.server.game.transaction;

import com.msg.MsgCommon;
import com.msg.MsgMain;
import com.msg.MsgRole;
import com.server.net.session.SessionManager;
import com.server.orm.OrmTransaction;
import com.server.orm.db.table.TB_role;
import com.server.orm.db.table.TB_token;
import com.server.orm.db.table.TB_user;

/**
 * 创建角色
 */
public class TCreateRole extends OrmTransaction {

    private String name;

    private String token;

    public TCreateRole(String name, String token) {
        this.name = name;
        this.token = token;
    }

    @Override
    public boolean action() {
        if (this.name.trim().isEmpty()) {
            return false;
        }
        TB_token tb_token = TB_token.get(token);//token是从server中取到得，不怕被重复多线程处理
        if (null == tb_token) {
            return false;
        }
        long userId = tb_token.getData().getUserId();
        TB_user tb_user = TB_user.get(userId);
        if (null == tb_user) {
            return false;
        }
        TB_user.B_user b_user = tb_user.getData();
        //限制创建新角色数量（默认1个）
        if (b_user.getRoleIds().size() >= 1) {
            return false;
        }
        //新建角色
        TB_role tb_role = new TB_role();
        TB_role.B_role b_role = tb_role.getData();
        b_role.setName(this.name);
        long roleId = TB_role.insert(tb_role);
        b_user.getRoleIds().add(roleId);
        tb_user.saveOrUpdate();//修改后执行，保证入库
        //反馈结果
        MsgMain.MainProtocl.Builder responseMsg = MsgMain.MainProtocl.newBuilder();
        MsgRole.SCCreateRole.Builder scmsg = MsgRole.SCCreateRole.newBuilder();
        MsgCommon.RoleLoginInfo.Builder newRole = MsgCommon.RoleLoginInfo.newBuilder();
        newRole.setRoleId(roleId);
        newRole.setName(this.name);
        scmsg.setNewRole(newRole);
        responseMsg.setMessageType(MsgMain.MessageType.SC_CreateRole);
        responseMsg.setSCCreateRole(scmsg);
        SessionManager.getInstance().sendMsgByUserId(userId, responseMsg);
        return true;
    }
}
